package cn.gjxblog.controller;

import cn.gjxblog.common.model.HttpResult;
import cn.gjxblog.model.dto.BlogQueryDTO;
import cn.gjxblog.model.entity.Blog;
import cn.gjxblog.model.vo.BlogVO;
import cn.gjxblog.service.BlogServcie;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.jsoup.Jsoup;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 作用:
 * 作者:gjx
 * 版本:V1.0
 * 创建时间: 2019/1/19 17:38
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private BlogServcie blogServcie;

    @RequestMapping("/queryBlog")
    public HttpResult<PageInfo<BlogVO>> queryBlog(@RequestBody BlogQueryDTO blogQueryDTO){
        PageInfo<Blog> pageInfo = blogServcie.queryBlog(blogQueryDTO.getBlog(),blogQueryDTO.getPageCondition().getPageNum(),blogQueryDTO.getPageCondition().getPageSize());
        List<BlogVO> page = pageInfo.getList().stream().map(blog -> blogTOVO(blog)).collect(Collectors.toList());
        PageInfo<BlogVO> newPageInfo = new PageInfo<>(page);
        newPageInfo.setTotal(pageInfo.getTotal());
        return HttpResult.success(newPageInfo);
    }

    private BlogVO blogTOVO(Blog blog){
        BlogVO blogVO = new BlogVO();
        BeanUtils.copyProperties(blog,blogVO);
        fillFileds(blogVO);
        return blogVO;
    }

    private void fillFileds(BlogVO blogVO) {
        String stripped =  Jsoup.parse(blogVO.getContent()).text();
        blogVO.setDigest(stripped.substring(0, Math.min(stripped.length(),40)));
        String tags = blogVO.getTags();
        blogVO.getTagList().addAll(Lists.newArrayList(Splitter.on(",").split(tags)));
    }


    @GetMapping("/getBlog")
    public HttpResult<BlogVO> getBlog(String id){
       Blog blog =  blogServcie.getBlog(id);
        BlogVO blogVO = blogTOVO(blog);
        return  HttpResult.success(blogVO);
    }
}
